package com.yzc.service;


import com.yzc.mapper.EmailMapper;
import com.yzc.model.query.system.UpdatePassReq;
import com.yzc.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Random;

import static com.yzc.result.ResultCodeEnum.*;

@Service
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;  // 注入 JavaMailSender

    @Autowired
    private EmailMapper emailMapper;

    @Value("${spring.mail.username}") // 获取配置中的发件人邮箱
    private String myEmail;

    public Result sendSimpleMessage(String emailAddress) {
        try {

            // 生成验证码
            String chekCode = generateSixDigitRandomNumberString();

            // 更新邮箱验证码
            int i = emailMapper.updateEmailChekCode(chekCode, emailAddress);

            if (i != 0) {
                // 邮箱更新成功，发送验证码邮件
                SimpleMailMessage message = new SimpleMailMessage();
                message.setFrom(myEmail);  // 设置发件人
                message.setTo(emailAddress);  // 设置收件人
                message.setSubject("yzc验证码测试");  // 设置邮件主题
                message.setText("验证码是：" + chekCode);  // 设置邮件内容

                // 发送邮件
                mailSender.send(message);

                // 返回成功的Result
                return Result.success("验证码已发送到邮箱");  // 自定义成功信息
            } else {
                // 如果没有更新到行，表示邮箱地址不存在
                return Result.fail(EMAIL_CHECK_FAIL);
            }
        } catch (MailException e) {
            // 处理邮件发送异常
            return Result.fail(EMAIL_SEND_FAIL);
        } catch (Exception e) {
            // 处理其他未知异常
            return Result.fail(SYSTEM_ERROR);
        }
    }


    public static String generateSixDigitRandomNumberString() {
        Random random = new Random();
        // 生成一个随机数，然后转换为字符串
        int randomNumber = random.nextInt(900000) + 100000;
        return String.valueOf(randomNumber);
    }

    public Result checkCode(String emailAddress, String chekCode) {
        int i = emailMapper.checkCode(emailAddress, chekCode);
        if (i != 0) {
            return Result.success("验证码正确");
        } else return Result.fail(BAD_REQUEST);
    }

    public Result updatePassword(UpdatePassReq updatePassReq) {
        int i = emailMapper.updatePassword(updatePassReq);
        if (i != 0) {
            return Result.success("密码修改成功");
        } else return Result.fail(BAD_REQUEST);
    }
}
